package handler;

import main.Utils;

import java.net.Socket;
import java.io.*;
import java.util.UUID;

/**
 * Created by IntelliJ IDEA.
 * User: qiukexu
 * Date: 2009-6-2
 * Time: 15:11:22
 */
public class BinaryHandler implements Handler {
    public void doHandle(Socket socket, int connectorNo) throws IOException {
        int exitCode = 3;
        int exitCount = 0;
        InputStream is = socket.getInputStream();
        OutputStream os = socket.getOutputStream();
        while(exitCount!=exitCode){
            byte[] read = new byte[1];
            int code = is.read(read);
            if(code !=-1 && code != 48) {
                System.out.println(transToBinary(read));
                UUID uuid = UUID.randomUUID();
                System.out.println(uuid.toString());
                os.write("\n\r".getBytes());
                byte[] output = new byte[16];
                long high = uuid.getMostSignificantBits();
                long lows = uuid.getLeastSignificantBits();
                output[0]=(byte)((high>>56) & 0xFF);
                output[1]=(byte)((high>>48) & 0xFF);
                output[2]=(byte)((high>>40) & 0xFF);
                output[3]=(byte)((high>>32) & 0xFF);
                output[4]=(byte)((high>>24) & 0xFF);
                output[5]=(byte)((high>>16) & 0xFF);
                output[6]=(byte)((high>>8) & 0xFF);
                output[7]=(byte)(high & 0xFF);
                output[8]=(byte)((lows>>56) & 0xFF);
                output[9]=(byte)((lows>>48) & 0xFF);
                output[10]=(byte)((lows>>40) & 0xFF);
                output[11]=(byte)((lows>>32) & 0xFF);
                output[12]=(byte)((lows>>24) & 0xFF);
                output[13]=(byte)((lows>>16) & 0xFF);
                output[14]=(byte)((lows>>8) & 0xFF);
                output[15]=(byte)(lows & 0xFF);
                os.write(output);
                os.write("\n\r".getBytes());
                os.flush();
                exitCount = 0;
            }
            else exitCount++;
        }
        System.out.println("exiting the connection...done.");
    }

    private String transToBinary(byte[] bytes){
        StringBuffer buffer = new StringBuffer();
        if(bytes == null) return null;
        for(int i=0;i<bytes.length;i++){
            buffer.append(Utils.appendToBinaryString(8,Long.toBinaryString(bytes[i])));
        }
        return buffer.toString();
    }

    public static void main(String[] args) {
        System.out.println(Integer.toBinaryString(-128));
    }
}
